package com.example.qrcode.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.example.qrcode.vo.ResultVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
public class OssController {

    // 阿里云OSS配置（建议移到配置文件中）
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tM2BfWHzFPYPB86qio1";
    private static final String ACCESS_KEY_SECRET = "MVYcQsyUbcXA1OJ5d9AQOERsbwoxek";
    private static final String BUCKET_NAME = "gdepri";

    @PostMapping("/upload")
    public ResultVo<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) {
        try {
            // 参数校验
            if (file == null || file.isEmpty()) {
                return ResultVo.error("请选择要上传的文件");
            }

            // 文件大小限制（例如限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return ResultVo.error("文件大小不能超过5MB");
            }

            System.out.println("开始上传文件: " + file.getOriginalFilename() + ", 大小: " + file.getSize());

            // 上传到阿里云OSS
            String url = uploadToOss(file);

            Map<String, Object> result = new HashMap<>();
            result.put("url", url);

            System.out.println("文件上传成功，URL: " + url);
            return ResultVo.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("文件上传失败: " + e.getMessage());
            return ResultVo.error("上传失败：" + e.getMessage());
        }
    }

    private String uploadToOss(MultipartFile file) throws Exception {
        System.out.println("=== 开始上传到OSS ===");

        // 最简单的OSS客户端创建方式
        OSS ossClient = new OSSClientBuilder()
                .build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null && originalFilename.contains(".")
                    ? originalFilename.substring(originalFilename.lastIndexOf("."))
                    : "";

            String fileName = "images/" + System.currentTimeMillis() + "_" +
                    UUID.randomUUID().toString().substring(0, 8) + fileExtension;

            System.out.println("上传文件名: " + fileName);

            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, file.getInputStream());
            ossClient.putObject(putObjectRequest);

            String url = "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + fileName;

            System.out.println("=== OSS上传完成 ===");
            return url;

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
                System.out.println("OSS客户端已关闭");
            }
        }
    }

}
